package ua.com.minus1.lookbattle;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.*;
import ua.com.minus1.lookbattle.models.CacheFolder;
import ua.com.minus1.lookbattle.models.Pair;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.ImageManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.status.BattleActivityStatus;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleCreator;
import ua.com.minus1.lookbattle.utils.BundleValues;

public class BattleActivityOld extends FragmentActivity implements View.OnClickListener
{
    private HttpManager httpManager;
    private ImageView imageL;
    private ImageView imageR;
    private ImageManager imageManager;
    private int catId;
    private String sessionId;
    private View imageLGroup;
    private View imageRGroup;
    private View progressL;
    private View progressR;
    private Pair lastResult;

    private CatsList catsList;
    private String uuid;
    private TextView clicksText;
    private AppPreferences appPreferences;
    private String lastUrl;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.battle);

        if(savedInstanceState != null) {
            BattleActivityStatus status = (BattleActivityStatus) savedInstanceState.getParcelable("status");
            lastResult = status.getLastResult();
            catId = status.getCatId();
            Log.i(BattleActivityOld.class.getName(), "restored saved state: pair: " + lastResult.toString() + " cat id: " + catId);
        } else
            catId = BundleCreator.readCategory(getIntent().getExtras());

        Toast.makeText(this, "Category id is: " + catId, Toast.LENGTH_SHORT).show();

        setupViews();

        appPreferences = new AppPreferences(this);
        uuid = appPreferences.getUUID();

        imageManager = new ImageManager(this, CacheFolder.IMAGES_BATTLE);
        httpManager = new HttpManager(this, CacheFolder.HTTP_BATTLE);

        if(lastResult != null)
            parseResult();
        else
            startBattle();
    }

    @Override
    protected void onResume() {
        updateClicks();
        super.onResume();
    }

    private void updateClicks()
    {
        clicksText.setText(String.valueOf(appPreferences.getClicks()));
    }

    private void startBattle() {
        clearContent(false);
        lastUrl = URLManager.getImagesURL(uuid, catId);
        httpManager.loadClass(lastUrl, Pair.class, new PairResultHandler(), HttpManager.USE_CACHE);
    }

    private void setupViews() {
        clicksText = (TextView) findViewById(R.id.clicksText);

        imageLGroup = findViewById(R.id.leftImage);
        imageRGroup = findViewById(R.id.rightImage);

        imageL = (ImageView) imageLGroup.findViewById(R.id.image);
        imageR = (ImageView) imageRGroup.findViewById(R.id.image);

        progressL = imageLGroup.findViewById(R.id.progress);
        progressR = imageRGroup.findViewById(R.id.progress);

        imageL.setOnClickListener(this);
        imageR.setOnClickListener(this);

        catsList = (CatsList) findViewById(R.id.battleCatList);
        catsList.setOnItemClickListener(new CatItemClickListener());
    }

    public void onClick(View view) {
        clearContent(true);
        int id = view.getId() == R.id.leftImage ? URLManager.IMAGE_LEFT : URLManager.IMAGE_RIGHT;
        lastUrl = URLManager.getImagesURL(uuid, catId, sessionId, id);
        httpManager.loadClass(lastUrl, Pair.class, new PairResultHandler(), HttpManager.USE_CACHE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if(lastResult != null) {
//            String[] images = {lastResult.imageL, lastResult.imageR};
            BattleActivityStatus status = new BattleActivityStatus();
            status.setStatus(lastResult, catId);
            outState.putParcelable("status", status);
//            BundleCreator.writeImages(outState, images);
//            BundleCreator.writeCacheUrl(outState, lastUrl);
//            BundleCreator.writeCategory(outState, catId);
        }
    }

    private void clearContent(boolean clearCache) {
        if (clearCache) {
            httpManager.clearCache();
            imageManager.clearCache();
        }
        imageL.setImageBitmap(null);
        imageR.setImageBitmap(null);
        progressL.setVisibility(View.VISIBLE);
        progressR.setVisibility(View.VISIBLE);
    }

    public void onMyLooksClick(View view) {
        Bundle extras = new Bundle();
        extras.putInt(BundleValues.CAT_ID, catId);
        Intent intent = new Intent(this, appPreferences.getRegistered()? LooksActivity.class: LoginActivity.class);
        intent.putExtras(extras);
        startActivity(intent);
    }

    class PairResultHandler implements HttpManager.HttpResultHandler<Pair>{
        public void onResultLoadComplete(Pair result) {
            Log.i(BattleActivityOld.class.getName(), "battle request result: " + result.toString());
            lastResult = result;
            appPreferences.setClicks(lastResult.cl);
            parseResult();
        }
    }

    private void parseResult()
    {
        loadImages(lastResult.imageL, lastResult.imageR);
        sessionId = lastResult.sessionId;
        updateClicks();
    }

    private void loadImages(String imageLURL, String imageRURL) {
        imageManager.loadBitmap(imageLURL,  imageL, new ImageManager.BitmapLoadListener() {
            public void onLoadComplete(Bitmap bitmap) {
                progressL.setVisibility(View.GONE);
            }
        }, ImageManager.USE_CACHE);
        imageManager.loadBitmap(imageRURL,  imageR, new ImageManager.BitmapLoadListener() {
            public void onLoadComplete(Bitmap bitmap) {
                progressR.setVisibility(View.GONE);
            }
        }, ImageManager.USE_CACHE);
    }

    private class CatItemClickListener implements CatsList.OnItemClickListener {
        public void onItemClick(CatItemFactory.CatItem catItem) {
            catId = catItem.catId;
            startBattle();
        }
    }
}
